﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NTQOnlineExam.Services.Models;

namespace NTQOnlineExam.Services.ReportService.Question
{
    public class QuestionReportService : IQuestionReportService
    {
        public IList<QuestionDTO> GetQuestions(string keyword, int termId, int sectionId, int pageIndex, int pageSize, string sorting, out int totalRecord)
        {
            var questionTable = DBCommand.DBCommand.CreateInstant().GetQuestionsDbCommand(keyword, termId, sectionId, pageIndex, pageSize, sorting, out totalRecord);
            var result = ConvertDataTableToQuestionDTO(questionTable);
            return result;
        }

        public IList<QuestionExamDTO> GetQuestionsForExamination(int sectionId, int termId, out int totalRecord)
        {
            var questionTable = DBCommand.DBCommand.CreateInstant().GetQuestionsDbCommand("", termId, sectionId, 0, 10000, null, out totalRecord);
            var result = ConvertDataTableToQuestionExamDTO(questionTable);
            return result;
        }

        private IList<QuestionDTO> ConvertDataTableToQuestionDTO(DataTable dtTable)
        {
            return (from DataRow dtRow in dtTable.Rows
                    select new QuestionDTO
                    {
                        AnswerId = (int)dtRow["AnswerId"],
                        QuestionId = (int)dtRow["QuestionId"],
                        TermId = (int)dtRow["TermId"],
                        SectionId = (int)dtRow["SectionId"],
                        Content = dtRow["Content"].ToString(),
                        CreateDate = Convert.ToDateTime(dtRow["CreateDate"]),
                        SectionName = dtRow["SectionName"].ToString(),
                        AnswerContent = dtRow["AnswerContent"].ToString(),
                        Explaination = dtRow["Explaination"].ToString(),
                        QuestionNumber = Convert.ToInt32(dtRow["RowNum"].ToString())
                    }).ToList();
        }

        private IList<QuestionExamDTO> ConvertDataTableToQuestionExamDTO(DataTable dtTable)
        {
            return (from DataRow dtRow in dtTable.Rows
                    select new QuestionExamDTO
                    {
                        AnswerId = (int)dtRow["AnswerId"],
                        QuestionId = (int)dtRow["QuestionId"]
                    }).ToList();
        }
    }
}
